package cn.com.ghy.android.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.webkit.URLUtil;
import android.widget.Toast;
import cn.com.ghy.android.util.CommonStatic;

public class AutoUpdateService {
	
	private int versionCode = 0; 
	@SuppressWarnings("unused")
	private String versionName = ""; 
	private String fileEx = ""; 
	private String fileNa = ""; 
	private String strURL = CommonStatic.URL_UPVERSION; 
	private ProgressDialog dialog;
	private Activity activity = null;
	private boolean isCancel = true;
	
	private static final String TAG = "AutoUpdateService";
	
	public AutoUpdateService(Activity activity) {
		this.activity = activity;
	}
	public int getCurrentVersion() { 
		try { 
			PackageInfo info = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0); 
			this.versionCode = info.versionCode; 
			System.out.println(this.versionCode);
			this.versionName = info.versionName; 
			System.out.println(this.versionName);
			return versionCode;
		  } catch (NameNotFoundException e) { 
			  e.printStackTrace(); 
		  } 
		  return 0;
	} 
	
	public void showUpdateDialog() { 
		  
		@SuppressWarnings("unused") 
		AlertDialog alert = new AlertDialog.Builder(activity)
			.setTitle("提示信息") 
			.setMessage("发现新版本,是否更新?")
			.setPositiveButton("更新",
					new DialogInterface.OnClickListener() { 
						public void onClick(DialogInterface dialog,int which) {
							boolean sdCardExist = Environment.getExternalStorageState()
							.equals(android.os.Environment.MEDIA_MOUNTED);
							if(!sdCardExist) {
								Toast.makeText(activity, "SD卡不存在,不能进行更新.", Toast.LENGTH_LONG).show();
							} else {
								showWaitDialog();
								downloadTheFile(strURL);
							}

						} 
					}).setNegativeButton("不更新",new DialogInterface.OnClickListener() { 
													public void onClick(DialogInterface dialog,int which) { 
														dialog.cancel(); 
														activity.finish();
													}
												}).show(); 
		  
	}
	
	public void showWaitDialog() { 
		dialog = new ProgressDialog(activity);
		dialog.setMessage("正在更新中,请稍后..."); 
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setMax(100);
		dialog.setIndeterminate(false); 
		dialog.setCancelable(false);
		dialog.setButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				isCancel = false;
				dialog.cancel();
				dialog.dismiss();
			}
		}); 
		dialog.show(); 
	} 
	
	private void downloadTheFile(final String strPath) { 
		fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length()).toLowerCase(); 
		fileNa = strURL.substring(strURL.lastIndexOf("/") + 1,strURL.lastIndexOf("."));
		try { 
			Runnable r = new Runnable() { 
				public void run() { 
					try { 
						doDownloadTheFile(strPath); 
					} catch (Exception e) { 
						Log.e(TAG, e.getMessage(), e); 
					} 
				} 
			};
			
			new Thread(r).start(); 
		} catch (Exception e) {   
			e.printStackTrace(); 
		}
	}
	
	private void doDownloadTheFile(String strPath) throws Exception { 
		if (!URLUtil.isNetworkUrl(strPath)) { 
		} else { 
			URL myURL = new URL(strPath); 
			URLConnection conn = myURL.openConnection(); 
			conn.connect(); 
			int versionSize = conn.getContentLength() / 1024;
			if(versionSize < 20) {
				dialog.cancel(); 
				dialog.dismiss(); 
				Looper.prepare();
				Toast.makeText(activity, "更新失败,请联系管理员.", Toast.LENGTH_LONG).show();
				Looper.loop();
				return;
			}
			InputStream is = conn.getInputStream(); 
			if (is == null) { 
				throw new RuntimeException("stream is null"); 
			} 
			File myTempFile = new File(Environment.getExternalStorageDirectory().getPath() + "/" + fileNa + "." + fileEx); 
			delFile(myTempFile);
			FileOutputStream fos = new FileOutputStream(myTempFile); 
			byte buf[] = new byte[1024]; 
			int temp = 0;
			do { 
				int numread = is.read(buf);
				if (numread <= 0) { 
					break; 
				}
				temp += numread / 1024;
				if(temp % (versionSize / 10) == 0) {
					dialog.incrementProgressBy(10);
				}
				fos.write(buf, 0, numread); 
			} while (isCancel); 
			fos.flush();
			if(isCancel) {
				dialog.cancel(); 
				dialog.dismiss();
				openFile(myTempFile); 
			} else {
				delFile(myTempFile);
			}
			try { 
				is.close(); 
			} catch (Exception ex) { 
				Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex); 
			}  
		} 
	} 
	
	private void openFile(File f) { 
		Intent intent = new Intent(); 
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
		intent.setAction(android.content.Intent.ACTION_VIEW); 
		String type = getMIMEType(f); 
		intent.setDataAndType(Uri.fromFile(f), type); 
		activity.startActivity(intent);
	} 
	
	public void delFile(File myFile) { 
		if (myFile.exists()) { 
			myFile.delete(); 
		}  
	} 
		  
	private String getMIMEType(File f) { 
		String type = ""; 
		String fName = f.getName(); 
		String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase(); 
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") 
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) { 
			type = "audio"; 
		} else if (end.equals("3gp") || end.equals("mp4")) { 
			type = "video"; 
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png") 
				|| end.equals("jpeg") || end.equals("bmp")) { 
			type = "image"; 
		} else if (end.equals("apk")) { 
			type = "application/vnd.android.package-archive"; 
		} else { 
			type = "*"; 
		} 
	  
		if (end.equals("apk")) {
			
		} else { 
			type += "/*"; 
		} 
	  
		return type;
	} 
}
